package com.wu.basic.dynamic.util;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class TTSUtil {

    /**
     * @param
     * @return
     * @describe 百度文字转换成语音
     * @author Jia wei Wu
     * @date 2021/3/2 9:36 下午
     **/
    public static File baiduTextToSpeech(String text) throws IOException {
        String url = "https://fanyi.baidu.com/gettts?lan=zh&text=%s&spd=5&source=wise";
        URL u = new URL(String.format(url, text));
        HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection();
        int statusCode = urlConnection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            System.out.println("Http错误码：" + statusCode);
        }
        InputStream is = urlConnection.getInputStream();
        File tempFile = new File("temp" + File.separator + text + ".mp3");
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        OutputStream out = new FileOutputStream(tempFile.getPath());
        int len = 0;
        byte[] b = new byte[2048];
        while ((len = is.read(b)) != -1) {
            out.write(b, 0, len);
        }
        return tempFile;
    }
}
